package com.example.myapplication;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Size;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FoodAcceptanceActivity extends AppCompatActivity {

    private PreviewView mCameraView;
    private TextView tvCurrentWeight;
    private TextView tvWeightDifference;
    private TextView tvOrderNumber;     // 订单号显示
    private TextView tvSchoolName;      // 学校名称显示
    private Button btnBack;
    private Button btnReset;
    private Button btnAccumulate;
    private Button btnRecord;
    private Button btnSubmitAcceptance;

    private static final int CAMERA_PERMISSION_REQUEST = 100;

    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private ExecutorService cameraExecutor;
    private ImageCapture imageCapture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_acceptance);

        // 初始化控件
        initViews();
        
        // 设置点击事件
        setListeners();
        
        // 初始化相机执行器
        cameraExecutor = Executors.newSingleThreadExecutor();
        
        // 检查相机权限
        checkCameraPermission();
        
        // 获取从上一个Activity传递过来的订单信息
        Intent intent = getIntent();
        if (intent != null) {
            String orderNumber = intent.getStringExtra("ORDER_NUMBER");
            String schoolName = intent.getStringExtra("SCHOOL_NAME");
            
            // 如果有订单信息，显示出来
            if (orderNumber != null && !orderNumber.isEmpty()) {
                tvOrderNumber.setText(orderNumber);
            }
            
            if (schoolName != null && !schoolName.isEmpty()) {
                tvSchoolName.setText(schoolName);
            }
        }
    }

    /**
     * 初始化控件的作用是将界面中的控件与变量关联起来，方便后续操作
     *
     */
    private void initViews() {
        mCameraView = findViewById(R.id.camera_view);
        tvCurrentWeight = findViewById(R.id.tv_current_weight);
        tvWeightDifference = findViewById(R.id.tv_weight_difference);
        tvOrderNumber = findViewById(R.id.tv_order_number);
        tvSchoolName = findViewById(R.id.tv_school_name);
        btnBack = findViewById(R.id.btn_back);
        btnReset = findViewById(R.id.btn_reset);
        btnAccumulate = findViewById(R.id.btn_accumulate);
        btnRecord = findViewById(R.id.btn_record);
        btnSubmitAcceptance = findViewById(R.id.btn_submit_acceptance);
    }

    /**
     * 设置点击事件的作用是给各个按钮添加点击事件，当用户点击按钮时，会执行相应的操作
     */
    private void setListeners() {
        // 返回按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        
        // 去皮按钮点击事件
        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(FoodAcceptanceActivity.this, "已去皮", Toast.LENGTH_SHORT).show();
                // 模拟去皮操作
                tvCurrentWeight.setText("0.00");
                tvWeightDifference.setText("比标准重量少0.15kg");
            }
        });
        
        // 累计按钮点击事件
        btnAccumulate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(FoodAcceptanceActivity.this, "已累计", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 记录按钮点击事件
        btnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(FoodAcceptanceActivity.this, "已记录", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 提交验收按钮点击事件
        btnSubmitAcceptance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(FoodAcceptanceActivity.this, "验收成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private void checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST);
        } else {
            // 已获得权限，初始化相机
            startCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startCamera();
            } else {
                Toast.makeText(this, "需要相机权限才能使用验收功能", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    private void startCamera() {
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();

                // 设置预览用例
                Preview preview = new Preview.Builder()
                        .build();

                // 设置相机选择器（前置或后置）
                CameraSelector cameraSelector = new CameraSelector.Builder()
                        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                        .build();

                // 设置图像分析用例
                ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                        .setTargetResolution(new Size(1280, 720))
                        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                        .build();

                // 设置图像分析器
                imageAnalysis.setAnalyzer(cameraExecutor, image -> {
                    // 这里可以处理相机捕获的图像
                    // 对于本任务，我们只需要显示预览，不需要特别的图像处理
                    image.close();
                });

                // 解除所有绑定的用例
                cameraProvider.unbindAll();

                // 绑定相机和用例
                cameraProvider.bindToLifecycle(
                        (LifecycleOwner) this,
                        cameraSelector,
                        preview,
                        imageAnalysis);

                // 连接预览到视图
                preview.setSurfaceProvider(mCameraView.getSurfaceProvider());

            } catch (ExecutionException | InterruptedException e) {
                // 处理相机初始化失败的情况
                Toast.makeText(this, "相机初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭相机执行器
        cameraExecutor.shutdown();
    }
}